package cn.wolfcode.car.business.util;

import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import com.github.pagehelper.util.StringUtil;
import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.UUID;

public class MinioUtils {
    public static String getUrl(MultipartFile file) throws Exception{
        // 主机地址
        String endpoint = "http://xue.cnkdl.cn:23900";
        // 账号
        String accessKey = "developer";
        // 密码
        String secretKey = "wolfcode.cn";
        // 存储空间
        String bucket = "car";
        InputStream stream = file.getInputStream();

        String fileName = UUID.randomUUID().toString();
        String extension = FileUploadUtils.getExtension(file);
        if (StringUtil.isNotEmpty(extension)) {
            fileName = fileName.concat(".").concat(extension);
        }

        //1 创建minio的链接对象
        MinioClient minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();
        //2 检查存储空间
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!exists) {
            throw new BusinessException("存储空间不存在!");
        }
        //3 上传文件
        PutObjectArgs build = PutObjectArgs.builder()
                .bucket(bucket)
                .object(fileName)
                .stream(stream, stream.available(), -1)
                .build();

        minioClient.putObject(build);
        //4 返回一个文件路径
        String url = endpoint + "/" + bucket + "/" + fileName;
        return url;
    }
}
